package com.kylin.common.saas.filter;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.kylin.common.core.exception.ServiceException;
import com.kylin.common.core.util.SpringUtils;
import com.kylin.common.saas.context.TenantContext;
import com.kylin.common.saas.context.TenantContextHolder;
import com.kylin.common.saas.datasource.DataSourceManager;
import com.kylin.common.security.filter.TenantFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * 租户过滤器
 * @author wuhao
 * @version 1.0 - 2023/4/23
 */
@Slf4j
public class SaasTenantFilter implements TenantFilter {

    private static final String TENANT_HEADER = "X-Tenant-ID";

    @Override
    public void destroy() {
        System.out.println("完成请求");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && StringUtils.isNotEmpty(((HttpServletRequest)request).getHeader(TENANT_HEADER))) {
            String tenantId = ((HttpServletRequest)request).getHeader(TENANT_HEADER);
            TenantContext context = new TenantContext(tenantId);
            TenantContextHolder.setContext(context);

            log.info("========================拦截数据源【" + tenantId +"】========================");
            DataSourceManager dataSourceManager = SpringUtils.getBean(DataSourceManager.class);
            DataSource dataSource = dataSourceManager.getDbSource(tenantId);
            // 如何获取当前数据源呢
            if (dataSource == null) {
                throw new ServiceException("当前租户未配置数据源，请联系管理员！");
            }
            try {
                DynamicDataSourceContextHolder.push(tenantId);
                chain.doFilter(request, response);
            } finally {
                DynamicDataSourceContextHolder.poll();
            }
            log.info("========================拦截数据源【end】========================");

        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig fConfig) throws ServletException {

    }
}
